<?php
require_once( 'XmlDocument.php' );

class XmlParser {

	var $oParser;
	var $oDocument;
	var $aElementStack;

	function XmlParser( ) {
		$this->oDocument     = null;
		$this->aElementStack = array();
		$this->oParser       = xml_parser_create();
		xml_set_object( $this->oParser, $this );
		xml_set_element_handler( $this->oParser, 'StartHandler', 'EndHandler' );
		xml_set_character_data_handler( $this->oParser, 'DataHandler' );
	}

	function Parse( $sXml, $sDocumentName = 'ParsedDocument' ) {

		$this->oDocument = new XmlDocument( $sDocumentName );
		xml_parse( $this->oParser, $sXml );
		xml_parser_free( $this->oParser );
		
		if ( $this->oDocument->HasStructure() ) {
			return $this->oDocument;
		}
		return false;
	}

	function StartHandler( $oParser, $sName, $aAttributes ) {
		$oThisElement = new XmlElement( $sName );
		$oThisElement->AddAttributes( $aAttributes );	
		array_push( $this->aElementStack, $oThisElement );
	}

	function EndHandler( $oParser, $sName ) {

		$oThisElement = array_pop( $this->aElementStack );

		if ( count( $this->aElementStack ) > 0 ) {
			$oThisElementsParent = array_pop( $this->aElementStack );
			$oThisElementsParent->AddElement( $oThisElement );
			array_push( $this->aElementStack, $oThisElementsParent );
		} else {
			$this->oDocument->AddElement( $oThisElement );
		}
	}

	function DataHandler( $oParser, $sData ){
		if ( trim( $sData ) != '' ) {
			$oThisElement = array_pop( $this->aElementStack );
			$oThisElement->SetContent( $sData );                  // TODO: Only supports one lot of content per tag
			array_push( $this->aElementStack, $oThisElement );
		}
	}
}
?>